package j.util.jdbc.simple.core;

import j.util.New;
import j.util.StringUtils;
import j.util.jdbc.simple.core.support.SqlUtils;
import j.util.jdbc.simple.metadata.TableMetaData;

import java.util.List;
import java.util.Map;

/**
 * 数据表的deelte操作语句的生成
 * @author 刘军海
 * @version Sep 14, 2011 10:01:07 AM
 */
public class SQLForDelete {

	private TableMetaData tmd;
	public SQLForDelete(TableMetaData tmd){
		this.tmd = tmd;
	}
	private String delSql;
	private List<String> delOrder;
	
	public List<String> getDeleteOrder() {
		return delOrder;
	}
	public String getDeleteSql(){
		if(StringUtils.isNullOrEmpty(delSql)){
			synchronized(this){
				if(StringUtils.isNullOrEmpty(delSql)){
					_createDeleteSql();
				}
			}
		}
		return this.delSql;
	}
	/**
	 * 根据pk生成delete语句，并同时生成order
	 */
	private void _createDeleteSql() {
		if(StringUtils.isNullOrEmpty(tmd.getPkColumns())){
			return;
		}
		this.delOrder = New.list();
		StringBuilder sql = new StringBuilder();
		sql.append("DELETE FROM ")
			.append(tmd.getTableName());
		String where = SqlUtils.fromCompositeColumnsToWhereSql(tmd.getPkColumns(), delOrder);
		sql.append(" WHERE ").append(where);
		delSql = sql.toString();
	}
	/**
	 * 根据实体的非空属性构造delete语句，语句之间以and连接
	 * 该生成方法将java的原生类型理解为非空，如int即使没有赋值，将也会是0
	 * @param args
	 * @param order
	 * @return
	 */
	public String generateDelSqlByCW(Map<String,Object> args,List<String> order){
		String retSql = "";
		String where = SqlUtils.fromArgsToWhereSql(tmd.getEntityAttributeColumnMap(), args, order);
		if(order.size()>0){
			StringBuilder sql = new StringBuilder("DELETE FROM ");
			sql.append(tmd.getTableName()).append(" WHERE ").append(where);
			retSql = sql.toString();
		}
		return retSql;
	}
}
